package com.imooc.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.imooc.enums.YesOrNo;
import com.imooc.mapper.UserAddressMapper;
import com.imooc.pojo.UserAddress;
import com.imooc.pojo.bo.AddressBO;
import com.imooc.service.AddressService;
import java.util.Date;
import java.util.List;
import lombok.AllArgsConstructor;
import org.n3r.idworker.Sid;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
public class AddressServiceImpl implements AddressService {

  private final UserAddressMapper userAddressMapper;

  private final Sid sid;

  @Transactional(rollbackFor = Exception.class, propagation = Propagation.SUPPORTS)
  @Override
  public List<UserAddress> queryAll(String userId) {
    return userAddressMapper
        .selectList(Wrappers.<UserAddress>lambdaQuery().eq(UserAddress::getUserId, userId));
  }

  @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
  @Override
  public void addNewUserAddress(AddressBO addressBO) {
    // 1. 判断当前用户是否存在地址，如果没有，则新增为‘默认地址’
    int isDefault = 0;
    List<UserAddress> addressList = this.queryAll(addressBO.getUserId());
    if (CollUtil.isEmpty(addressList)) {
      isDefault = 1;
    }
    String addressId = sid.nextShort();
    // 2. 保存地址到数据库
    UserAddress newAddress = new UserAddress();
    BeanUtils.copyProperties(addressBO, newAddress);
    newAddress.setId(addressId);
    newAddress.setIsDefault(isDefault);
    newAddress.setCreatedTime(new Date());
    newAddress.setUpdatedTime(new Date());
    userAddressMapper.insert(newAddress);
  }

  @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
  @Override
  public void updateUserAddress(AddressBO addressBO) {
    String addressId = addressBO.getAddressId();
    UserAddress pendingAddress = new UserAddress();
    BeanUtils.copyProperties(addressBO, pendingAddress);
    pendingAddress.setId(addressId);
    pendingAddress.setUpdatedTime(new Date());
    userAddressMapper.updateById(pendingAddress);
  }

  @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
  @Override
  public void deleteUserAddress(String userId, String addressId) {
    UserAddress address = new UserAddress();
    address.setId(addressId);
    address.setUserId(userId);
    userAddressMapper.deleteById(address);
  }

  @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
  @Override
  public void updateUserAddressToBeDefault(String userId, String addressId) {
    // 1. 查找默认地址，设置为不默认
    List<UserAddress> list = userAddressMapper
        .selectList(Wrappers.<UserAddress>lambdaQuery().eq(UserAddress::getUserId, userId)
            .eq(UserAddress::getIsDefault, YesOrNo.YES.type));
    for (UserAddress ua : list) {
      ua.setIsDefault(YesOrNo.NO.type);
      userAddressMapper.updateById(ua);
    }
    // 2. 根据地址id修改为默认的地址
    UserAddress defaultAddress = new UserAddress();
    defaultAddress.setId(addressId);
    defaultAddress.setUserId(userId);
    defaultAddress.setIsDefault(YesOrNo.YES.type);
    userAddressMapper.updateById(defaultAddress);
  }

  @Transactional(rollbackFor = Exception.class, propagation = Propagation.SUPPORTS)
  @Override
  public UserAddress queryUserAddres(String userId, String addressId) {
    return userAddressMapper
        .selectOne(Wrappers.<UserAddress>lambdaQuery().eq(UserAddress::getId, addressId)
            .eq(UserAddress::getUserId, userId));
  }
}